<template>
  <div id="main">
    <van-sticky>
      <div class="navBar">
        <div class="navBar-left">
          <img :src="back" alt="" @click="handleBack" class="back">
          <div v-if="user" class="avatar" :style="{backgroundImage: `url(${dataList.avatar ? store.state.imgUrl + dataList.avatar : logo})`}"></div>

          <!-- <van-image
              v-if="user"
              width="30"
              height="30"
              round
              :src="dataList.avatar ? store.state.imgUrl + dataList.avatar : logo"/> -->
          <div v-if="user" style="font-size:16px;color:#fff;padding:0 5px">
            {{ dataList.name }}
          </div>
        </div>
        <div class="nav-btn" v-if="user && !dataList.isOwn == 0">
          <div class="nav-btn-follow" v-if="!dataList.isAttention" @click="handleLike(dataList.userId)">
            <van-icon name="plus"/>
            <span>关注</span>
          </div>
          <div class="nav-btn-followed" v-if="dataList.isAttention" @click="handleLike(dataList.userId)">
            <span>已关注</span>
          </div>
          <!-- <van-button v-if="isfollow" plain  icon="plus" color="#f29600" size="mini">关注</van-button>
          <van-button v-if="isfollow" color="#fff"  plain size="mini" ><span style="color:#000" >已关注</span></van-button> -->
        </div>
      </div>
    </van-sticky>
    <div class="middle">
      <!-- 文章标题 -->
      <div class="title">
        {{ dataList.title }}
      </div>
      <!-- 作者信息 -->
      <div class="info" ref="user">
        <div class="info-l" @click="gotoPersonal(dataList)">
          <div class="avatar" :style="{backgroundImage: `url(${dataList.avatar ? store.state.imgUrl + dataList.avatar : logo})`}"></div>

          <!-- <van-image
              width="38"
              height="38"
              style="border:1px solid #ccc"
              round
              :src="dataList.avatar ? store.state.imgUrl + dataList.avatar : logo"/> -->
          <div class="user">
            <div class="name">{{ dataList.name }}<span class="me" v-if="dataList.isOwn == 0">我</span></div>
            <div class="time-ip">{{ dataList.createTime }} · 来自{{ dataList.ipProvince ? dataList.ipProvince : '未知' }}</div>
          </div>
        </div>
        <div class="info-r" v-if="!dataList.isOwn == 0">
          <van-button v-if="!dataList.isAttention" icon="plus" color="#f29600" size="mini"
                      @click="handleLike(dataList.userId)">关注
          </van-button>
          <van-button v-if="dataList.isAttention" color="#ccc" plain size="mini" @click="handleLike(dataList.userId)">
            <span style="color:#000">已关注</span></van-button>
        </div>
      </div>
      <!-- 文章配图 -->
      <!-- <div class="images">
        <img :src="store.state.imgUrl + dataList.thumbnail" alt="" width="100%" height="100%">
      </div> -->
      <!-- 文章内容 -->
      <div class="desc" v-html="dataList.textContent">
      </div>
      <!-- 评论 -->
      <div class="comment" ref="comments">
        <div class="comment-title">
          <span>评论</span>
          <span class="comment-num">{{ dataList.commentNum }}</span>
        </div>
        <CommentList
            v-if="show"
            :token="token"
            :userId="dataList.userId"
            ref="commentList"
            :source="dataList.id"
            :list="commentList"
            class="article-list"
            @update-total-count="totalCommentCount = $event"
            @reply-click="onReplyClick"
            @del-comment="handleDel"
        ></CommentList>
      </div>
    </div>
    <!-- 评论框 -->
    <div class="field" v-if="commentShow">
      <van-button
          class="comment-btn"
          type="default"
          round
          size="small"
          @click="handleClear"
      >我来说一下我的想法
      </van-button>
    </div>
    <!-- 底部导航 -->
    <div class="bottom">
      <div @click="gotodz(dataList)" class="icon">
        <img :src="remarkList.urldz" width="15" v-if="!dataList.isLike"/>
        <img :src="remarkList.urldzlove" v-if="dataList.isLike" width="15"/>
        <div class="icon-txt">{{ dataList.likeNum }}</div>
      </div>
      <div class="icon">
        <img :src="remarkList.urlpl" width="15" @click="isPostShow = true"/>
        <div class="icon-txt">{{ dataList.commentNum }}</div>
      </div>
      <div @click="addCollect(dataList)" class="icon">
        <img :src="remarkList.urlsc" width="16" v-if="!dataList.isCollect"/>
        <img :src="remarkList.urlsclove" width="16" v-if="dataList.isCollect"/>
        <div class="icon-txt">{{ dataList.collectNum }}</div>
      </div>
      <div @click="gotozf(dataList)" class="icon">
        <img :src="remarkList.urlzf" width="15"/>
        <div class="icon-txt">分享</div>
      </div>
    </div>
    <!-- 评论发布 -->
    <van-popup v-model="isPostShow" position="bottom" round>
      <!-- 这里使用 v-if 的目的是让组件伴随着弹出层的显示进行渲染和销毁，防止加载过的组件不重新渲染导致数据不会重新加载的问题 🌟🌟  -->
      <PostComment
          v-if="isPostShow"
          :target="replyComment.id"
          @post-scucces="onPostSuccess"
          ref="myInput"
          @close="isPostShow = false"
          :art_id="dataList.id"
      ></PostComment>
    </van-popup>
    <!-- <van-share-sheet
        v-model="showShare"
        title="立即分享给好友"
        :options="options"
        @select="onSelect"
    /> -->
  </div>
</template>

<script>
import CommentList from "@/views/share/components/comment-list";
import PostComment from "@/views/share/components/post-comment"
import {queryArticleDetailApi, addAuthorLike, updateLikes, addCollect, deleteComment} from '@/api/share.js'
import store from '@/store'
import {Toast} from "vant";
import {Dialog} from 'vant';
import {antiShake} from '@/utils/antie.js'//防抖函数
export default {
  components: {
    CommentList,
    PostComment
  },
  data() {
    return {
      store: store,
      user: false,
      back: require("@/assets/search/back.png"),
      // headImg: require("@/assets/touxiang.png"),
      isfollow: false,
      // articleImg: require("@/assets/articleImg.png"),
      articleContent: '九月的海拉尔，动听的马头琴声隐隐约约，仿佛从草原深处传来。有彩带河风雨后彩虹下盛开的格桑花，有呼伦贝尔古城喜庆繁忙的老街烟火，有天边彩霞里广袤草原无以伦比的秋色……九月的海拉尔，蔚蓝的天空下，在塔台上俯瞰千里草原，云起时七彩斑斓，瑰丽无限。霞落后起起伏伏一望无际。海拉尔的九月就像调色板一样魔幻而美丽……',
      value: '',
      remarkList: {
        urlsclove: require('@/assets/remark/sc_love.png'),
        urldzlove: require('@/assets/remark/dz_love.png'),
        urldz: require('@/assets/remark/dz.png'),
        urlpl: require('@/assets/remark/pl.png'),
        urlsc: require('@/assets/remark/sc.png'),
        urlzf: require('@/assets/remark/zf.png'),
      },
      commentList: [],
      replyComment: {}, //  当前回复评论对象
      isPostShow: false,// 发布评论
      totalCommentCount: 0, // 评论数量
      id: '',
      dataList: {},
      sourceId: '',
      show: false,
      commentShow: false,
      token: '',
      options: [
        {name: '微信', icon: 'wechat', openType: 'share'},
        {name: 'QQ', icon: 'qq', openType: 'share'},
        {name: '微博', icon: 'weibo'},
        {name: '复制链接', icon: 'link'},

      ],
      showShare: false,
      logo: require("@/assets/tx.png"),
      reply: false
    }
  },
  mounted() {
    window["getInfoFromFlutter"] = (info) => {
      if (JSON.parse(info).action === 'share') {
        this.getInfoFromFlutter(info)
      }
    };
    this.handleScrollx()
    window.addEventListener('scroll', this.handleScrollx, true)

    this.id = !this.getParam("id") ? "" : this.getParam("id")
    this.token = !this.getParam("token") ? "" : decodeURI(this.getParam("token"))
    this.getDataList()


  },
  created() {

  },
  beforeDestroy() {    //在加载时添加了scroll监听，如果不销毁，到下一个页面时，没有主动销毁，会报错'offsetTop' of undefined。因此，需要在页面跳转前销毁此监听
    window.removeEventListener("scroll", this.handleScrollx, true)
  },
  methods: {
    getParam(name) {
      if (window.location.hash.indexOf("?") != -1) {
        const query = window.location.hash.split("?")[1];
        const vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
          var pair = vars[i].split("=");
          if (pair[0] == name) {
            return pair[1];
          }
        }
      } else {
        return "";
      }
    },
    getInfoFromFlutter(info) {
      let data = JSON.parse(info)
      if (data.param.succeed == 1) {
        this.$toast.success('分享成功')
      } else {
        this.$toast.fail('已取消分享')
      }
    },
    handleBack() {
      this.$router.go(-1)
      let message = {
        action: 'showBottom',
        param: {}
      }
      getInfoFromVue.postMessage(JSON.stringify(message))
    },
    handleScrollx() {//监听头部导航

      // const navBarTop = this.$refs.user.getBoundingClientRect().top
      // console.log(this.$refs.user.getBoundingClientRect().top)
      if (this.$refs.user.getBoundingClientRect().top <= 20) {
        this.user = true
      } else {
        this.user = false
      }
      const commentSection = this.$refs.comments;
      const rect = commentSection.getBoundingClientRect();
      const windowHeight = window.innerHeight || document.documentElement.clientHeight;

      if (rect.bottom >= 0 && windowHeight - rect.top > 100) {
        this.commentShow = true
      } else {
        this.commentShow = false
      }
    },
    onReplyClick(comment) {
      this.reply = false
      // 获取当前评论
      this.replyComment = comment
      // 打开回复评论弹窗
      this.isPostShow = true
    },
    onPostSuccess(comment) {
      const commentNew = comment
      if (this.reply) {
        commentNew.reply = ''
      }
      this.$store.commit('share/UPDATE_COMMENT_LIST', commentNew)
      this.dataList.commentNum += 1
      // 关闭发布评论弹出层
      this.isPostShow = false
    },
    handleClear() {
      this.isPostShow = true
      this.reply = true
      this.replyComment.id = ''

    },
    handleOpen() {
      this.isPostShow = true
    },
    getDataList() {
      let data = {
        id: this.id,
        token: this.token
      }
      queryArticleDetailApi(data).then((res) => {
        this.show = true
        this.$nextTick(() => {
          this.$refs.commentList.init()
        })
        this.dataList = res.data
      })
    },
    handleLike: antiShake( function (id){
      if (!this.dataList.isAttention) {
          this.likeSure(id)
      }else{
        this.tipIsAttention(id)
      }
     
    }),
    likeSure(id){
       let data = {
        id: id,
        token: this.token
      }
      addAuthorLike(data).then((res) => {
        // this.getDataList()
        this.dataList.isAttention = !this.dataList.isAttention
        if (this.dataList.isAttention) {
          this.$toast.success('关注成功')
        } else {
          this.$toast.fail('已取消关注')
        }

      })
    },
      //取消关注提示
    tipIsAttention(id){
      Dialog.confirm({
        title: '提示',
        message: '您确定要取消关注该用户吗？',
        confirmButtonColor: 'rgba(242, 150, 0, 1)'
      }).then(() => {
        this.likeSure(id)
        this.$toast.success("取关成功");
         
      }).catch(err => {
        
      })
    }, 
    //点赞
    gotodz: antiShake( function (item) {
      let data = {
        id: item.id,
        type: 0, //文章，动态，视频是0 评论是1
        token: this.token
      }
      updateLikes(data).then((res) => {
        if (res.code == 0) {
          if (item.isLike) {
            this.$toast.fail('已取消点赞')

          } else {
            this.$toast.success('点赞成功')

          }
          this.dataList.isLike = !this.dataList.isLike
          this.dataList.likeNum += this.dataList.isLike ? 1 : -1;
        }
      }).catch((err) => {
        this.$toast.fail('点赞失败')
      })
    }),
    // 收藏
    addCollect: antiShake( function (item) {
      let data = {
        id: item.id,
        type: 0, //文章，动态，视频是0 评论是1
        token: this.token
      }
      addCollect(data).then((res) => {
        if (res.code === 0) {
          console.log(item.isCollect)
          if (item.isCollect) {
            this.$toast.fail('已取消收藏')
          } else {
            this.$toast.success('收藏成功')
          }
          this.dataList.isCollect = !this.dataList.isCollect
          this.dataList.collectNum += this.dataList.isCollect ? 1 : -1;
        }
      }).catch((err) => {
        this.$toast.fail('收藏失败')
      })
    }),
    // 分享
    gotozf(item) {
      // this.showShare = true
      let message = {
        action: 'share',
        param: {
          type: "link",            //必填
          title: item.title,          //必填
          name: '/home/share/articleDetail',
          subtitle: item.description,
          link: "http://192.168.110.105:9033/#/articleDetail?" + item.id,//动态列表的详情?id:''
          callback: 1
        }
      }
      getInfoFromVue.postMessage(JSON.stringify(message))
    },
    onSelect(option) {
      Toast(option.name);
      if (option.name === '微信') {
        window.location.href = 'weixin://';
      } else if (option.name === 'qq') {
        //跳转qq链接
      } else if (option.name === '微博') {
        //跳转微博的链接
      } else if (option.name === '复制链接') {
        //复制链接
        this.copyLink()
      }
      this.showShare = false;
    },
    copyLink() {
      const link = window.location.href; // 要复制的链接
      // console.log(link)
      // 使用Vant的Clipboard组件的copy方法复制链接
      // this.$vant.Clipboard.copy(link)
      //   .then(() => {
      //     this.$toast('链接已复制'); // 复制成功提示
      //   })
      //   .catch(() => {
      //     this.$toast('复制失败'); // 复制失败提示
      //   });
      let inputNode = document.createElement('input')  // 创建input
      inputNode.value = link // 赋值给 input 值
      document.body.appendChild(inputNode) // 插入进去
      inputNode.select() // 选择对象
      document.execCommand('Copy') // 原生调用执行浏览器复制命令
      inputNode.className = 'oInput'
      inputNode.style.display = 'none' // 隐藏
      this.$toast.success('复制成功')
    },
    //删除评论
    handleDel(comment) {
      this.$store.commit('share/DELETE_COMMENT_LIST', comment)
      
      if (comment.children.length > 0) {//如果子集有评论则删除数量应该加上子集数量
        this.dataList.commentNum -= 1 + comment.children.length
      }else{
         this.dataList.commentNum -= 1
      }
      deleteComment(comment.id).then((res) => {
        if (res.code === 0) {
          this.$toast('已删除该评论')
        }
      }).catch((err) => {
        this.$toast('评论删除失败')
      })
    },
     // 跳转到主页
    gotoPersonal(item) {
      if (item.isOwn == 0) {//跳转到自己的个人主页
        this.$router.push({path: '/personalPage',query:{}})
      }else{//跳转到别人主页的个人主页
        this.$router.push({path: '/visitPersonal',query:{obj:JSON.stringify(item)}})
      }
      
      // let message = {
      //   action: 'hiddenBottom',
      //   param: {}
      // }
      // getInfoFromVue.postMessage(JSON.stringify(message))
    }
  }
}
</script>

<style lang="less" scoped>
#main {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;

  .navBar {
    height: 40px;
    background: #f29600;
    display: flex;
    padding: 2px 19px;
    align-items: center;
    justify-content: space-between;

    .navBar-left {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .avatar{
          background-size: 100%;
          width: 30px;
          height: 30px;
          border-radius: 50%;
          opacity: 1;
          margin-left:10px;
          background-repeat: no-repeat;
          background-position: center;
          background-size: cover;
      }
    }

    .van-image {
      margin: 0 10px;
    }

    .nav-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;

      .nav-btn-follow {
        background: #fff;
        color: #f29600;
        border: 1px solid #fff;
        padding: 3px;
      }

      .nav-btn-followed {
        background: #f29600;
        color: #fff;
        border: 1px solid #fff;
        padding: 3px;
      }
    }
  }

  .middle {
    flex: 1;
    overflow-x: hidden;
    padding-bottom: 72px;
    padding: 10px 10px;
    padding-bottom: 72px;

    .title {
      font-size: 18px;
      font-weight: 700;
      letter-spacing: 0px;
      line-height: 26.06px;
      color: rgba(0, 0, 0, 1);
    }

    .info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0;
      // font-size: 12px;
      .info-l {
        display: flex;
        height: 38px;
        align-items: center;
        justify-content: flex-start;
        .avatar{
          background-size: 100%;
          width: 38px;
          height: 38px;
          border-radius: 50%;
          opacity: 1;
          margin-right:5px;
          background-repeat: no-repeat;
          background-position: center;
          background-size: cover;
        } 
        .user {
          padding: 0 10px;

          .name {
            font-size: 16px;
            font-size: 16px;
            font-weight: 500;
            letter-spacing: 0px;
            line-height: 23.17px;
            color: rgba(0, 0, 0, 1);
            text-align: left;
            vertical-align: top;
            .me{
              background: #ccc6;
              padding: 0 3px;
              font-size: 14px;
              border-radius: 5px;
              color: #9b9494;
              margin: 0 5px;
            }
          }

          .time-ip {
            font-size: 12px;
            font-weight: 400;
            letter-spacing: 0px;
            line-height: 17.38px;
            color: rgba(102, 102, 102, 1);
          }
        }
      }

    }

    .images {
      position: relative;
      overflow: hidden;
      // display: flex;
      .img {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        min-width: 100%;
        min-height: 100%;

      }
    }

    .desc {
      padding: 10px 0;
      font-size: 17px;
      font-weight: 400;
      letter-spacing: 0px;
      line-height: 24.62px;
      border-bottom: 1px solid #f5f7fa;

      /deep/ img {
        width: 100%;
      }
    }

    .comment {
      // padding:5px 17px 0 17px;
      padding: 5px;

      .comment-title {
        font-size: 17px;
        font-size: 17px;
        font-weight: 500;
        letter-spacing: 0px;
        line-height: 24.62px;

        .comment-num {
          padding-left: 5px;
        }
      }
    }
  }

  .bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 20px;
    background: #fff;
    display: flex;
    justify-content: space-between;
    padding: 8px 17px;
    font-size: 12px;

    .icon {
      display: flex;
      align-items: center;
      justify-content: center;

      .icon-txt {
        margin-left: 5px;
      }
    }
  }

  .field {
    position: fixed;
    bottom: 36px;
    left: 0;
    right: 0;
    height: 30px;
    background: #fff;
    display: flex;
    justify-content: space-between;
    padding: 8px 17px;
    font-size: 12px;

    .comment-btn {
      width: 357px;
      height: 30px;
      font-size: 15px;
      color: #a7a7a7;
      border-radius: 15px;
      border: solid 1px #eeeeee;
      background: #f7f8fa;
    }

  }
}
</style>